package com.ygsoft.nio.filereceiver;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class ClientWorker extends Thread {
	
	private SocketChannelQueue queue = null;
	private Selector selector = null;
	private ByteBuffer readBuffer;
	
	public ClientWorker(SocketChannelQueue queue){
		this.queue = queue;
		try {
			this.selector = Selector.open();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		this.readBuffer = ByteBuffer.allocate(4096);
	}
	
	public Selector getReadSelector(){
		return this.selector;
	}
	
	public void run(){
		System.out.println("Active Worker Thread ..");
		int sCount = 0;
		while(true)
		{
			try {
				sCount = this.selector.select();
				if(sCount > 0){
					System.out.println("Proc Request ..");
					procRequest();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	private void procRequest() throws IOException {
		Iterator<SelectionKey> iter = this.selector.selectedKeys().iterator();
		
		while(iter.hasNext()){
			SelectionKey key = iter.next();
			iter.remove();
			
			if(!key.isValid() || !key.channel().isOpen() 
					|| ((SocketChannel)key.channel()).socket().isClosed()){
				System.out.println(">Invalid key..");
				key.cancel();
				continue;
			}
			
			try{
				System.out.println("Read Data..");
				this.readData(key);
			}catch(IOException e){
				System.out.println("Invalid Key..");
				key.cancel();
				key.channel().close();
			}
		}
	}
	
	private void readData(SelectionKey key) throws IOException {
		SocketChannel sChannel = (SocketChannel)key.channel();
//		if(!(sChannel.isConnected() && sChannel.isOpen())) {
//			key.cancel();
//			return;
//		} 
		int rCount = sChannel.read(this.readBuffer);
		if(rCount == -1){
			System.out.println("Socket is closed..");
			key.cancel();
			return ;
		}
		this.readBuffer.flip();
		StringBuffer requestString = (StringBuffer)key.attachment();
		requestString.append(new String(this.readBuffer.array()));
		
		this.readBuffer.clear();
		
		System.out.println("Request >" + requestString);
	}
	
}
